package madixin.t445;


import java.util.Stack;

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        //LisNode转stack
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        Stack<Integer> stackResult = new Stack<Integer>();

        while (l1 != null) {
            s1.push(l1.val);
            l1 = l1.next;
        }

        while (l2 != null) {
            s2.push(l2.val);
            l2 = l2.next;
        }

        int flag = 0;//初始化进位符
        while (!s1.isEmpty() || !s2.isEmpty() || flag == 1) {

            int num = flag;
            if (!s1.isEmpty()) {
                num += s1.pop();
            }

            if (!s2.isEmpty()) {
                num += s2.pop();
            }

            if (num >= 10) {
                num = num % 10;
                flag = 1;
            } else {
                flag = 0;
            }

            stackResult.push(num);
        }


        //stack转LisNode
        if (stackResult.isEmpty()) {
            return null;
        }

        ListNode result = new ListNode(stackResult.pop());
        ListNode current = result;

        while (!stackResult.isEmpty()) {
            ListNode tmp = new ListNode(stackResult.pop());
            current.next = tmp;
            current = current.next;
        }

        return result;
    }
}